package com.lykj.llw.box.ui.activity

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.dinuscxj.itemdecoration.LinearDividerItemDecoration
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.lykj.lib_base.base.BaseActivity
import com.lykj.lib_base.constants.BConstants
import com.lykj.lib_base.internal.extfun.clickWithTrigger
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.lib_base.net.http.CustomResponseBodyObserver
import com.lykj.lib_base.net.http.RetrofitManager
import com.lykj.llw.box.R
import com.lykj.llw.box.adapter.sale.RoleBuyAdapter
import com.lykj.llw.box.data.bean.response.RoleBuyListResponse
import com.lykj.llw.box.databinding.ActRoleBuyBinding
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody

/**
 * ================================================
 * 角色购买页面
 * ================================================
 *
 * @author gosha
 * @date 2023/10/20-14:34
 */
class RoleBuyActivity : BaseActivity() {
    lateinit var binding: ActRoleBuyBinding

    private val mAdapter = RoleBuyAdapter()
    private val mData = ArrayList<RoleBuyListResponse.DataDTO.RowsDTO>()

    private var currentPage = 1
    private val pageSize = 10
    private var totalPage = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActRoleBuyBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initUI()
        initData()
        setListener()
    }

    override fun onResume() {
        super.onResume()

        ImmersionBar
            .with(this)
            .statusBarDarkFont(true) //状态栏字体是深色，不写默认为亮色
            .navigationBarDarkIcon(true)
            .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
            .navigationBarEnable(false)
            .init()

        obtainRoleBuy("1")
    }

    override fun initUI() {
        binding.titleBar.tvTitle.text = "账号交易"
        binding.titleBar.tvRightOption.text = "购买记录"

        initRCV()
    }

    private fun initRCV() {
        val linearLayoutManager = LinearLayoutManager(this)
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        binding.rcvBuy.layoutManager = linearLayoutManager
        binding.rcvBuy.setHasFixedSize(true)

        val dividerItemDecoration = LinearDividerItemDecoration(
            this, LinearDividerItemDecoration.LINEAR_DIVIDER_VERTICAL
        )
        dividerItemDecoration.setDivider(
            resources.getDrawable(
                R.drawable.divider_15dp, resources.newTheme()
            )
        )
        binding.rcvBuy.addItemDecoration(dividerItemDecoration, 0)
        mAdapter.data = mData
        val emptyView = View.inflate(this, R.layout.empty_playing, null)
        emptyView.findViewById<TextView>(R.id.tv_desc).text = "暂无交易数据"
        mAdapter.setEmptyView(emptyView)
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val intent = Intent(this@RoleBuyActivity, RoleBuyDetailActivity::class.java)
            intent.putExtra("id", mData[position].id)
            startActivity(intent)
        }
        binding.rcvBuy.adapter = mAdapter
    }

    //获取交易信息
    private fun obtainRoleBuy(status: String) {
        clearBodyParam()
        initBodyParam()
        bodyParams["status"] = status
        bodyParams["pageNo"] = currentPage
        bodyParams["pageSize"] = pageSize
        bodyParams["gameName"] = "${binding.etSearch.text}"
        RetrofitManager.instance.obtainRoleBuy(object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@RoleBuyActivity, d)
            }

            override fun specificHandle(responseBody: String) {
                //解析gson
                var bean = GsonUtils.fromJson(
                    responseBody, RoleBuyListResponse::class.java
                )

                mData.clear()
                totalPage = bean.data.totalPage
                if (bean.data.rows.isNotEmpty()) {
                    mData.addAll(bean.data.rows)
                }
//                else {
//                    if (currentPage == 1) {
//                        ToastUtils.showShort(this@RoleBuyActivity, "暂无可交易角色")
//                    }
//                }
                mAdapter.notifyDataSetChanged()
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(this@RoleBuyActivity, msg)
                }
            }
        }, bodyParams)
    }

    override fun initData() {
    }

    override fun setListener() {
        binding.titleBar.ivBack.clickWithTrigger {
            finish()
        }

        binding.titleBar.tvRightOption.clickWithTrigger {
            startActivity(Intent(this@RoleBuyActivity, BuyRecordActivity::class.java))
        }

        binding.lltPullDown.clickWithTrigger {
//            ToastUtils.showShort(this, "显示筛选框")
        }

        binding.lltRole.clickWithTrigger {
            val intent = Intent(this, CommonWebViewActivity::class.java)
            intent.putExtra("title", "必看规则")
            intent.putExtra("url", BConstants.USER_PROTOCOL)
            startActivity(intent)
        }

        binding.srfTrading.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                currentPage = 1
                mData.clear()

                obtainRoleBuy("1")

                refreshLayout.finishRefresh(350, true, false)
                refreshLayout.resetNoMoreData()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (currentPage == totalPage) {
                    refreshLayout.finishLoadMoreWithNoMoreData()
                    ToastUtils.showShort(this@RoleBuyActivity, "没有更多交易数据了")
                    return
                }
                currentPage++
                obtainRoleBuy("1")
                refreshLayout.finishLoadMore(350)
            }
        })

        KeyboardUtils.registerSoftInputChangedListener(this) { height ->
            if (height == 0) {
                binding.etSearch.clearFocus()
            }
        }


        binding.ivSearchDelete.clickWithTrigger {
            binding.etSearch.setText("")
            obtainRoleBuy("1")
        }

        binding.etSearch.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                //保存关键字
                KeyboardUtils.hideSoftInput(this)
                obtainRoleBuy("1")
            }
            true
        }
    }

    override fun onDestroy() {
        removeDisposables(this)
        super.onDestroy()
    }
}